package com.lagou.lagourocketmq.controller;

import com.alibaba.fastjson.JSON;
import com.lagou.lagourocketmq.config.RedisLock;
import com.lagou.lagourocketmq.mapper.SkuMapper;
import com.lagou.lagourocketmq.pojo.Order;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.redisson.api.RBucket;
import org.redisson.api.RKeys;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class SecondKillController {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RedisLock redisLock;

    @RequestMapping("/secondKill")
    public String buy() throws UnsupportedEncodingException {

        Boolean skuLock = redisLock.lock("skuLock");
        if(skuLock == true){
            try{
                RBucket<Object> bucket = redissonClient.getBucket("sku:123");

                if(bucket.get() == null){
                    Integer skuMapperOne = skuMapper.findOne("123");
                    bucket.set(skuMapperOne);
                }
                Object redisSkuacount = bucket.get();
                Integer skuNum = (Integer) redisSkuacount;
                if(skuNum > 0){
                    System.out.println("订单号："+skuNum);
                    Order order = new Order(skuNum,"123",6000, UUID.randomUUID().toString(),"nopay");
                    //将order转成json字符串
                    String orderStr = JSON.toJSONString(order);

                    RBucket<Object> bucket1 = redissonClient.getBucket("order:" + order.getOrderId());

                    bucket1.setAsync(orderStr,20,TimeUnit.SECONDS);
                    //将json字符串发给mq
                    SendResult sendResult = rocketMQTemplate.syncSend("lagou-orderDelay", MessageBuilder.withPayload(orderStr).build(),2000,3);
                    skuNum-=1;
                    bucket.set(skuNum);
                }else {
                    return "sold out";
                }
            }finally {
                redisLock.unlock("skuLock");
            }

        }

        return "buy success";
    }

    @RequestMapping("/warrnup")
    public String warrnup() {
        RBucket<Object> bucket = redissonClient.getBucket("sku:123");

        Integer skuacount = skuMapper.findOne("123");
//        System.out.println(skuacount);
        bucket.set(skuacount);

        return "warrnup success";
    }


    @RequestMapping("/paybill")
    public String paythebill(){

        RKeys keys = redissonClient.getKeys();
        Iterable<String> keysByPattern = keys.getKeysByPattern("order:*");
        for(String key:keysByPattern){
            RBucket<Object> bucket = redissonClient.getBucket(key);
            String order = (String)bucket.get();
            Order orderobj = JSON.parseObject(order, Order.class);
            orderobj.setStatus("paid");
            bucket.set(JSON.toJSONString(orderobj),20, TimeUnit.SECONDS);
            System.out.println("order:"+orderobj.getOrderId()+" 支付成功");

        }

        return "pay success";
    }


    @RequestMapping("/redisacount")
    public String redisacount(){

        RBucket<Object> bucket = redissonClient.getBucket("sku:123");
        Integer acount = (Integer) bucket.get();
        if(acount ==null){
            return "null";
        }
        return String.valueOf((int)acount);

    }

}
